package handler.bid

/*
	ibid公司打卡服务
*/
import service.CardService

import util.Utils

import java.text.SimpleDateFormat

// 显示一个公司所有打卡器
handler.get('/ibid/card/get-scaner-meeting-list'){req, resp ->
	String companyIdStr = req.params.companyId
	if(!companyIdStr || !Utils.isIdValid(companyIdStr)){
		resp.json([error: 'parameter-invalid'])
		return
	}
	int companyId = companyIdStr as int

	if(!req.session('user') || req.session('user').companyId != companyId){
		resp.json([error: 'session-invalid'])
		return
	}

	def ll = CardService.getScanerListByCompanyId(companyId)

	def scanerList = ll.grep{it.type == 'scaner'}
	def meetingList = ll.grep{it.type == 'meeting'}

	resp.json([scanerList: scanerList, meetingList: meetingList])
}

// 显示一个公司的一周的打卡记录统计，从周日开始
handler.get('/ibid/card/get-record-stat'){req, resp ->
	String companyIdStr = req.params.companyId
	if(!companyIdStr || !Utils.isIdValid(companyIdStr)){
		resp.json([error: 'parameter-invalid'])
		return
	}
	int companyId = companyIdStr as int

	if(!req.session('user') || req.session('user').companyId != companyId){
		resp.json([error: 'session-invalid'])
		return
	}

	// date query
	String fm = 'yyyy-MM-dd'
	String date = req.params.date
	def begin
	if(date && date ==~ /^\d{4}\-\d{2}\-\d{2}$/){
		begin = Date.parse(fm, date)
	}else{
		def dd = new Date()
		begin = dd - dd.day

		date = begin.format(fm)
	}

	def dateEndDd = begin + 7
	String dateEnd = dateEndDd.format(fm)

	log.info(date + ' - ' + dateEnd)

	// scaner/meeting query
	int scanerId = 0
	String scanerIdStr = req.params.scanerId
	if(scanerIdStr && Utils.isIdValid(scanerIdStr)){
		scanerId = scanerIdStr as int
	}

	def ll = CardService.getCompanyRecordList(companyId, date, dateEnd, scanerId)
	resp.json([ll: ll, date: date, dateEnd: dateEnd])
}

// 显示打卡器二维码页面
handler.get('/ibid/card/scaner'){req, resp ->
	String scanerIdStr = req.params.scanerId
	if(!scanerIdStr || !Utils.isIdValid(scanerIdStr)){
		resp.json([error: 'parameter-invalid'])
		return
	}
	int scanerId = scanerIdStr as int

	def item = CardService.getScanerName(scanerId)
	if(!item){
		resp.json([error: 'scaner-not-exist'])
		return
	}

	// 如果是会议，判断时效
	if('meeting' == item.type && !CardService.isScanerMeetingValid(scanerId)){
		String fm = 'yyyy-MM-dd HH:mm:ss'
		resp.render('/card/scaner-meeting-fail.tpl', [scanerId: scanerId, 
			scanerName: item.name, 
			companyName: item.companyName, 
			beginTime: item.beginTime.format(fm), 
			endTime: item.endTime.format(fm), 

			beforeMin: item.beforeMillis ? item.beforeMillis / 1000 / 60 : 0, 
			afterMin: item.afterMillis ? item.afterMillis / 1000 / 60 : 0
			])
		return
	}

	resp.render('/card/scaner.tpl', [scanerId: scanerId, 
		scanerName: item.name, 
		companyName: item.companyName])
}